package com.xb.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xb.model.domain.entity.PopupDetails;
import com.xb.system.mapper.db1.PopupDetailsMapper;
import com.xb.system.service.PopupDetailsService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PopupDetailsServiceImpl extends ServiceImpl<PopupDetailsMapper, PopupDetails>
        implements PopupDetailsService {

    @Override
    public List<PopupDetails> getActivePopups() {
        LambdaQueryWrapper<PopupDetails> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(PopupDetails::getIsDeleted, 0)  // 未删除
                .ge(PopupDetails::getExpirationDate, LocalDateTime.now())  // 未过期
                .orderByDesc(PopupDetails::getDisplayOrder);  // 按优先级降序

        return this.list(queryWrapper);
    }
    
    /**
     * 获取最新的有效套餐信息
     * @return 套餐信息
     */
    @Override
    public Map<String, Object> getActivePackages() {
        Map<String, Object> result = new HashMap<>();
        
        // 获取所有有效的广告弹窗信息
        List<PopupDetails> popupList = getActivePopups();
        if (popupList.isEmpty()) {
            log.warn("未找到有效的套餐配置");
            return result;
        }

        try {
            // 遍历所有弹窗数据
            for (PopupDetails popup : popupList) {
                if (popup.getVipPackages() == null || popup.getVipPackages().isEmpty()) {
                    continue;
                }
                
                // 获取套餐类型（使用scrollingInfo作为类型）
                String packageType = popup.getScrollingInfo();
                
                // 解析JSON数据为套餐列表
                ObjectMapper mapper = new ObjectMapper();
                List<Map<String, Object>> packages = mapper.readValue(
                    popup.getVipPackages(), 
                    new TypeReference<List<Map<String, Object>>>() {}
                );
                
                // 直接将解析后的原始数据放入结果中
                result.put(packageType, packages);
            }
            
        } catch (Exception e) {
            log.error("解析套餐数据失败", e);
        }
        
        return result;
    }

    /**
     * 从时长字符串中提取天数
     */
    private int extractDays(String duration) {
        try {
            // 提取数字部分
            String numStr = duration.replaceAll("[^0-9]", "");
            return Integer.parseInt(numStr);
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 获取最新的有效广告弹窗信息
     * @return 最新的广告弹窗或null
     */
    private PopupDetails getLatestPopup() {
        LambdaQueryWrapper<PopupDetails> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(PopupDetails::getIsDeleted, 0)  // 未删除
                .ge(PopupDetails::getExpirationDate, LocalDateTime.now())  // 未过期
                .orderByDesc(PopupDetails::getDisplayOrder, PopupDetails::getId)  // 按优先级降序，然后按ID降序
                .last("limit 1");  // 只取一条

        return this.getOne(queryWrapper);
    }
}